import React from 'react';
import { Form, Input, Button, Select, Message } from 'antd';
import { connect } from 'react-redux';
import { login } from 'Actions/userAction';
import { BROWSER_MODE } from 'Constants/webConstants';
import Api from 'Utils/api';
import * as routerActions from 'react-router-redux';
import TitleButton from 'Component/Page/Components/TitleButton';
import { chaeckMobilePhone, checkLandLineTel } from '../../../../utils/index';
import { CAPTCHA_SECONDS } from '../../../../constants/config';
import './index.scss';

const Option = Select.Option;
const FormItem = Form.Item;
let canSendCaptcha = true;
const CaptchaSeconds = CAPTCHA_SECONDS;
class ExamLogin extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      testTypes: [],
      remainingSecond: CaptchaSeconds
    };
    this.IsVertical = BROWSER_MODE.isVertical(this.props.mode);
    this.sendCaptcha = ::this.sendCaptcha;
    this.countDownSeconds = ::this.countDownSeconds;
  }
  componentWillUnmount() {
    clearInterval(this.timer);
  }
  componentWillMount() {
    this.initTestType();
    canSendCaptcha = true;
  }
  onTest() {
    this.props.form.validateFieldsAndScroll((err) => {
      if (!err) {
        const formValue = this.props.form.getFieldsValue();
        const values = Object.values(formValue);
        if (!this.validation(values)) {
          Message.error('请完善信息');
          return;
        }
        // 检查手机号格式
        if (!chaeckMobilePhone(formValue.phone) && !checkLandLineTel(formValue.phone)) {
          document.getElementById('phone').setAttribute('placeholder', '请输入正确的联系方式');
          this.props.form.setFields({ phone: { value: '', errors: [new Error(' ')] } });
          return;
        }
        const self = this;
        const api = new Api({
          method: 'POST',
          path: '/testers/user',
          data: {
            name: formValue.name,
            id_no: formValue.cardId,
            phone: formValue.phone,
            code: formValue.code
          },
          success: ((json) => {
            self.props.dispatch(login({ ...json, testID: formValue.type }));
            self.props.dispatch(routerActions.push('/interactive/knowledge/exam_detail'));
          }),
          error: (msg) => {
            Message.error(msg);
          }
        });
        api.run();
      }
    });
  }
  validation(value) {
    for (let i = 0, len = value.length; i < len; i++) {
      if (!value[i]) {
        return false;
      }
    }
    return true;
  }
  initTestType() {
    const api = new Api({
      method: 'GET',
      path: '/subjects',
      success: (res) => {
        this.setState({
          testTypes: res
        });
      },
      error: () => {}
    });
    api.run();
  }
  // 发送验证码
  sendCaptcha() {
    const phone = this.props.form.getFieldsValue().phone;
    if (!canSendCaptcha) {
      return;
    }

    if (!phone) {
      this.props.form.setFields({ phone: { value: phone, errors: [new Error(' ')] } });
      return;
    }

    if (!chaeckMobilePhone(phone) && !checkLandLineTel(phone)) {
      document.getElementById('phone').setAttribute('placeholder', '请输入正确的联系方式');
      this.props.form.setFields({ phone: { value: '', errors: [new Error(' ')] } });
      return;
    }
    canSendCaptcha = false;
    setTimeout(() => {
      this.setState({
        remainingSecond: CaptchaSeconds,
      }, () => {
        this.countDownSeconds();
      });
    }, 0);

    const api = new Api({
      method: 'POST',
      path: '/phone/verify_code',
      data: {
        phone,
        response: 'tmind'
      },
      error: () => {
        this.setState({
          remainingSecond: 0,
        }, () => {
          canSendCaptcha = true;
          clearInterval(this.timer);
          this.timer = undefined;
        });
      },
    });
    api.run();
  }
  /**
   * 验证码倒计时
   */
  countDownSeconds() {
    const remainingSecond = this.state.remainingSecond - 1;
    if (remainingSecond < 0) {
      canSendCaptcha = true;
      clearInterval(this.timer);
      this.timer = undefined;
    } else {
      if (!this.timer) {
        this.timer = setInterval(this.countDownSeconds, 1000);
      }
      this.setState(preState => (Object.assign({}, preState, {
        remainingSecond,
      })));
    }
  }
  render() {
    const { testTypes, remainingSecond } = this.state;
    const { form } = this.props;
    const { getFieldDecorator } = form;
    if (this.IsVertical) {
      return (
        <div className="v-login-page">
          <div className="login-wrap" >
            <TitleButton title="测评登录" />
            <div className="knowledage-login">
              <Form className="login-form" >
                <FormItem label="姓名" >
                  {getFieldDecorator('name', {})(
                    <Input placeholder="请输入姓名" />
                  )}
                </FormItem >
                <FormItem label="身份证号" >
                  {getFieldDecorator('cardId', {})(
                    <Input placeholder="请输入身份证号" />
                  )}
                </FormItem >
                <FormItem label="联系电话" >
                  {getFieldDecorator('phone', {})(
                    <Input placeholder="请输入联系电话" />
                  )}
                  <Button className="code" onClick={this.sendCaptcha}>
                    {remainingSecond === 60 || remainingSecond === 0
                      ? '获取验证码'
                      : <span>剩余{remainingSecond}s</span>
                    }
                  </Button>
                </FormItem>
                <FormItem label="验证码">
                  {getFieldDecorator('code', {})(
                    <Input placeholder="请输入验证码" />
                  )}
                </FormItem>
                <FormItem label="测试类别">
                  {getFieldDecorator('type', {
                  })(
                    <Select placeholder="请选择测试类别">
                      {
                        testTypes ? testTypes.filter(item => item.state).map((item) => {
                          return <Option key={item.id}>{item.type}</Option>;
                        }) : undefined
                      }
                    </Select>
                  )}
                </FormItem >
              </Form >
            </div >
            <div className="evaluate" onClick={this.onTest.bind(this)} >
              <img src="images/icon_evaluate.png" alt="我要测评" />
              <span >我要测评</span >
            </div >
          </div >
        </div>
      );
    }
    return (
      <div className="login-page" >
        <div className="login-wrap" >
          <TitleButton title="知识测评" />
          <div className="knowledage-login">
            <Form className="login-form" >
              <FormItem label="姓名" >
                {getFieldDecorator('name', {
                  rules: [
                    { required: true, message: ' ' }
                  ]
                })(
                  <Input placeholder="请输入姓名" />
                )}
              </FormItem >
              <FormItem label="身份证号" >
                {getFieldDecorator('cardId', {
                  rules: [
                    { required: true, message: ' ' }
                  ]
                })(
                  <Input placeholder="请输入身份证号" />
                )}
              </FormItem >
              <FormItem label="联系电话" >
                {getFieldDecorator('phone', {
                  rules: [
                    { required: true, message: ' ' }
                  ]
                })(
                  <Input placeholder="请输入联系电话" id="phone" />
                )}
                <Button className="code" onClick={this.sendCaptcha}>
                  {remainingSecond === 60 || remainingSecond === 0
                    ? '获取验证码'
                    : <span>剩余{remainingSecond}s</span>
                  }
                </Button>
              </FormItem>
              <FormItem label="验证码">
                {getFieldDecorator('code', {
                  rules: [
                    { required: true, message: ' ' }
                  ]
                })(
                  <Input placeholder="请输入验证码" />
                )}
              </FormItem>
              <FormItem label="测试类别">
                {getFieldDecorator('type', {
                  rules: [
                    { required: true, message: ' ' }
                  ]
                })(
                  <Select placeholder="请选择测试类别" style={{ width: 366 }}>
                    {
                      testTypes
                      ? testTypes.filter(item => item.state).map((item) => {
                        return <Option key={item.id}>{item.type}</Option>;
                      }) : undefined
                    }
                  </Select>
                )}
              </FormItem >
            </Form >
          </div >
          <div className="evaluate" onClick={this.onTest.bind(this)} >
            <img src="images/icon_evaluate.png" alt="我要测评" />
            <span >我要测评</span >
          </div >
        </div >
      </div >
    );
  }
}

function mapStateToProps(state) {
  return {
    ...state.routing,
    ...state.webReducer,
  };
}

export default Form.create()(connect(mapStateToProps)(ExamLogin));

